#include "paint_system.h"
#ifndef HEAD_Q_H
#include "../head_Q.h"
#endif

#ifndef FACILITY_H
#endif

#ifndef FACILITY_DEFINE_H
#endif
#include <QPainter>

PaintSystem::PaintSystem(QGraphicsScene * scene)
    :scene(scene){

}

QPixmap PaintSystem::generateQPixmapWithString(std::string &hashid){
    QPixmap pix;
    QString _id = QString::fromStdString(hashid);
    if (_id.length() != shape::STD_LENGTH_SERIALIZED_STRING) {
        return QPixmap(); // 返回空 QPixmap 表示错误
    }

    // 拆分 _id 为四个部分
    QString part1 = _id.mid(0, 2);
    QString part2 = _id.mid(2, 2);
    QString part3 = _id.mid(4, 2);
    QString part4 = _id.mid(6, 2);

    // 加载四个部分的图片
    QImage image3(QString("%1/%2.png").arg(CARGO_SRC).arg(part1));
    if(!image3.isNull()) image3 = image3.scaled(CARGO_SHOW_LENTH, CARGO_SHOW_LENTH).transformed(QTransform().rotate(180));
    QImage image4(QString("%1/%2.png").arg(CARGO_SRC).arg(part2));
    if(!image4.isNull())image4 = image4.scaled(CARGO_SHOW_LENTH, CARGO_SHOW_LENTH).transformed(QTransform().rotate(270));
    QImage image1(QString("%1/%2.png").arg(CARGO_SRC).arg(part3));
    if(!image1.isNull())image1 = image1.scaled(CARGO_SHOW_LENTH, CARGO_SHOW_LENTH).transformed(QTransform().rotate(0));
    QImage image2(QString("%1/%2.png").arg(CARGO_SRC).arg(part4));
    if(!image2.isNull())image2 = image2.scaled(CARGO_SHOW_LENTH, CARGO_SHOW_LENTH).transformed(QTransform().rotate(90));

    // 创建一个带透明背景的 QImage
    QImage combinedImage(CARGO_SHOW_LENTH, CARGO_SHOW_LENTH, QImage::Format_ARGB32);
    combinedImage.fill(Qt::transparent);
    int s = CARGO_SHOW_LENTH / 2;
    // 在 QImage 上绘制四个部分
    QPainter painter(&combinedImage);
    // painter.drawImage()
    if(!image4.isNull())painter.drawImage(QRect(0, 0, s, s), image4);
    if(!image3.isNull())painter.drawImage(QRect(0, s, s, s), image3);
    if(!image1.isNull())painter.drawImage(QRect(s, 0, s, s), image1);
    if(!image2.isNull())painter.drawImage(QRect(s, s, s, s), image2);

    return QPixmap::fromImage(combinedImage);


    return pix;
}

void PaintSystem::drawColorCargo(int x, int y,gate::GateDirection g, char _id, Cargo * cargo){
    QImage image(QString("%1/%2").arg(STATIC_CARGO_SRC).arg(_id));
    if(!image.isNull()) image = image.scaled(CARGO_SHOW_LENTH, CARGO_SHOW_LENTH);
    QGraphicsPixmapItem *item = scene->addPixmap(QPixmap::fromImage(image));
    item->setZValue(CARGO_LEVEL);
    cargo->object_qt = item;
    cargo->obj_moveTo(x,y,g);
}

void PaintSystem::drawShapeCargo(int x, int y,gate::GateDirection g, ShapeCargo* shape){
    std::string hash_id = shape->define->hash_id;
    QPixmap pix = generateQPixmapWithString(hash_id);
    QGraphicsPixmapItem *item = scene->addPixmap(pix);
    item->setZValue(CARGO_LEVEL);
    shape->object_qt = item;
    shape->obj_moveTo(x,y,g);

} // 根据cargo 和 位置绘制




